package com.xsherl.leetcode.solution;

import com.xsherl.leetcode.base.ListNode;

public class RotateList {

    /**
     * 将链表右移k个位置，就是将尾部第k个节点设置为新头节点，尾部第k+1个节点为新尾结点
     */
    public ListNode rotateRight(ListNode head, int k) {
        if (head == null || head.next == null){
            return head;
        }
        ListNode tail = head;
        int len = 1;
        while (tail.next != null){
            len++;
            tail = tail.next;
        }
        int i = 1;
        k = k % len;
        if (k == 0){
            return head;
        }
        tail.next = head;
        ListNode newHead = head, newTail = tail;
        while (i <= (len - k)){
            newHead = newHead.next;
            newTail = newTail.next;
            i++;
        }
        newTail.next = null;
        return newHead;
    }

    public static void main(String[] args) {
        int[] nums = {1, 2, 3};
        int k = 1;
        ListNode head = ListNode.build(nums);
        ListNode listNode = new RotateList().rotateRight(head, k);
        System.out.println(listNode);
    }
}
